// Package utils
// @Author: zhangdi
// @File: startup
// @Version: 1.0.0
// @Date: 2023/5/22 13:30
package utils

import (
	"bytes"
	"html/template"
	"io/ioutil"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
)

// DisableAutoStart 取消开机自启

func enableAutoStartLinux(appName string) error {
	cmd := exec.Command("systemctl", "enable", appName+".service")
	return cmd.Run()
}

func disableAutoStartLinux(appName string) error {
	cmd := exec.Command("systemctl", "disable", appName+".service")
	return cmd.Run()
}

func enableAutoStartMacos(appName string) error {

	const plist = `<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>{{.AppName}}</string>
        <key>ProgramArguments</key>
        <array>
            <string>{{.AppPath}}</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
    </dict>
    </plist>`

	// 获取当前用户信息
	u, err := user.Current()
	if err != nil {
		return err
	}

	// 解析模板文件
	tpl, err := template.New("").Parse(plist)
	if err != nil {
		return err
	}

	// 组织模板数据
	data := struct {
		AppName string
		AppPath string
	}{
		AppName: "com.example." + appName,
		AppPath: filepath.Join(GetRootDir(), appName),
	}

	// 渲染模板
	var buf bytes.Buffer
	if err := tpl.Execute(&buf, data); err != nil {
		return err
	}

	// 写入plist文件
	launchAgentsDir := filepath.Join(u.HomeDir, "Library/LaunchAgents")
	if err := os.MkdirAll(launchAgentsDir, 0755); err != nil {
		return err
	}
	plistPath := filepath.Join(launchAgentsDir, data.AppName+".plist")
	if err := ioutil.WriteFile(plistPath, buf.Bytes(), 0644); err != nil {
		return err
	}

	// 加载配置
	if _, err := os.Stat(plistPath); err == nil {
		cmd := exec.Command("launchctl", "load", plistPath)
		if err := cmd.Run(); err != nil {
			return err
		}
	}

	return nil
}

func disableAutoStartMacos(appName string) error {
	// 获取当前用户信息
	u, err := user.Current()
	if err != nil {
		return err
	}

	// 卸载配置
	appPlist := filepath.Join(u.HomeDir, "Library/LaunchAgents/com.example."+appName+".plist")
	cmd := exec.Command("launchctl", "remove", appPlist)
	if err = cmd.Run(); err != nil {
		return err
	}

	// 删除plist文件
	err = os.Remove(appPlist)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	return nil
}
